package cn.sczhyt.modules.szhy.service.impl;

import cn.sczhyt.common.exception.RRException;
import cn.sczhyt.common.utils.*;
import cn.sczhyt.modules.app.entity.UserEntity;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.sczhyt.modules.szhy.dao.MeetingFileDao;
import cn.sczhyt.modules.szhy.entity.MeetingFileEntity;
import cn.sczhyt.modules.szhy.service.MeetingFileService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Service("meetingFileService")
public class MeetingFileServiceImpl extends ServiceImpl<MeetingFileDao, MeetingFileEntity> implements MeetingFileService {
    @Autowired
    private MeetingFileDao meetingFileDao;


    /**
     * 文件配置
     */
    @Value("${cn.sczhyt.szhy.file.upload-path}")
    private  String filePath;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MeetingFileEntity> page = this.page(
                new Query<MeetingFileEntity>().getPage(params),
                new QueryWrapper<MeetingFileEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 创建者  罗世杰
     * 创建日期 2020/10/28
     * 描述 会议文件保存
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveMeetingFile(MultipartFile[] files, String meetingId) {
        if (files != null && files.length > 0) {
            //根据时间创建文件夹
            Date date = new Date();
            String datefile = DateUtils.format(date, "yyyyMMdd");
            //创建文件名
            String filename = UUIDUtils.getUUID();
            //会议文件存储的路径

            String realPath = filePath.concat(datefile);

            File path = new File(realPath);
            if (!path.exists()) {
                path.mkdirs();
            }
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                System.out.println("文件大小为:" + file.getSize() / 1024);
                //保存文件
                if (!file.isEmpty()) {
                    try {
                        //转存文件 file.getOriginalFilename()：文件原名称包括后缀名
                        String originalFilename = file.getOriginalFilename();
                        //原文件名的后缀名
                        String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
                        //文件存储位置
                        String filepath = realPath + "/" + filename + "." + substring;

                        System.out.println(filepath);

                        file.transferTo(new File(filepath));
                        //上传成功后对路径及文件名进行处理
                        MeetingFileEntity meetingFileEntity = new MeetingFileEntity();
                        meetingFileEntity.setMeetingId(meetingId);
                        meetingFileEntity.setFileName(originalFilename);
                        meetingFileEntity.setFilePath(filepath);
                        meetingFileEntity.setFileSize((int) (file.getSize() / 1024));
                        meetingFileEntity.setCreateTime(new Date());
                        meetingFileDao.insert(meetingFileEntity);

                    } catch (IOException e) {
                        e.printStackTrace();
                        throw new RRException("会议文件保存失败!", 201);
                    }
                }
            }
        }
    }

    @Override
    public IPage<MeetingFileEntity> findAll(Integer page, Integer limit, String meetingId) {

        Page<MeetingFileEntity> pages = new Page<>(page, limit);

        return meetingFileDao.findAll(pages, meetingId);
    }

    @Override
    public R delect(String Id) {


        System.out.println(Id);

        MeetingFileEntity meetingFileEntity = meetingFileDao.selectById(Id);
        meetingFileDao.deleteById(Id);
        File file = new File(meetingFileEntity.getFilePath());
        if (file.exists()) {
            file.delete();
            return R.ok();
        } else {
            return R.error(400, "删除的文件不存在！");
        }
    }

    @Override
    public void download(String id, HttpServletResponse response, HttpServletRequest request){
        MeetingFileEntity meetingFileEntity = meetingFileDao.selectById(id);
        File file = new File(meetingFileEntity.getFilePath());
        try {
            DownloadFileUtils.downloadFile(meetingFileEntity.getFileName(), file, response, request);
        } catch (UnsupportedEncodingException e) {
            throw new RRException("文件下载出错",201);
        }
    }

    @Override
    public IPage<MeetingFileEntity> appFindAll(UserEntity user, Integer page, Integer limit, String meetingId) {

        Page<MeetingFileEntity> pages = new Page<>(page, limit);

        return meetingFileDao.appFindAll(user.getUserId(),pages, meetingId);

    }
}
